package xml

import (
	"encoding/xml"
	"fmt"
	"io/ioutil"
	"os"
)

type PersonXml struct {
	XMLName xml.Name `xml:"person"`
	Name    string   `xml:"name"`
	Age     int      `xml:"age"`
	Email   string   `xml:"email"`
}

func XmlMarshal() {

	p := PersonXml{Name: "tom", Age: 20, Email: "tom@gmail.com"}
	// 没有缩进
	// b, _ := xml.Marshal(p)
	// 缩进  前缀  缩进字符
	b, _ := xml.MarshalIndent(p, "", "	")
	fmt.Printf("string(b): \n%v\n", string(b))
}

func ReadXml() {
	b, _ := ioutil.ReadFile("a.xml")
	var p PersonXml
	xml.Unmarshal(b, &p)
	fmt.Printf("p: %v\n", p)
}

func WriteXml() {
	p := PersonXml{
		Name:  "Bob",
		Age:   30,
		Email: "BOB@gmail.com",
	}

	f, _ := os.OpenFile("a.xml", os.O_WRONLY, 0777)
	defer f.Close()
	e := xml.NewEncoder(f)
	e.Encode(p)

}
